<?php

class SiteController extends Controller
{
    public $layout = 'shop';

    /**
     * Declares class-based actions.
     */
    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError()
    {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * Displays the contact page
     */
    public function actionContact()
    {
        $model = new ContactForm;
        if (isset($_POST['ContactForm'])) {
            $model->attributes = $_POST['ContactForm'];
            if ($model->validate()) {
                $headers = "From: {$model->email}\r\nReply-To: {$model->email}";
                mail(Yii::app()->params['adminEmail'], $model->subject, $model->body, $headers);
                Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');
                $this->refresh();
            }
        }
        $this->render('contact', array('model' => $model));
    }

    /**
     * Displays the login page
     */
    public function actionLogin()
    {
        if (!Yii::app()->user->isGuest) {
            $this->redirect('/shop');
        }
        if (!defined('CRYPT_BLOWFISH') || !CRYPT_BLOWFISH)
            throw new CHttpException(500, "This application requires that PHP was compiled with Blowfish support for crypt().");

        $loginModel = new LoginForm('Front');

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($loginModel);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $loginModel->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if ($loginModel->validate() && $loginModel->login())
                $this->redirect(Yii::app()->user->returnUrl);
        }

        $registerModel = new Users;
        // collect user input data
        if (isset($_POST['Users'])) {
            $registerModel->attributes = $_POST['Users'];
            if ($registerModel->save()) {
                $loginModel->attributes = $_POST['Users'];
                // validate user input and redirect to the previous page if valid
                if ($loginModel->validate() && $loginModel->login())
                    $this->redirect(Yii::app()->user->returnUrl);
            }

        }
        // display the login form
        $this->render('login', array('loginModel' => $loginModel, 'registerModel' => $registerModel));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout()
    {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }
    
    /**
     * forget password
     */
    public function actionForgot()
    {
        $forgotModel = new ForgotForm('Front');

        // collect user input data
        if (isset($_POST['ForgotForm'])) {
            $forgotModel->attributes = $_POST['ForgotForm'];
            // validate user input and redirect to the previous page if valid
            $user = Users::model()->find('LOWER(email)=?', array(strtolower($forgotModel->email)));
            if ($forgotModel->validate() && $user) {
                $mailer = Yii::app()->Mailer;
                $mailer->ClearAddresses();
                $to = $forgotModel->email;
                $subject = 'Reset Password';
                $message = $this->renderPartial('forgot_template', array('link' => 'http://'. $_SERVER['SERVER_NAME']. '/site/reset/id/' . $user->id),true);
                $fromName = 'Petitpoint';
                try {
                    $mailer->sendEmail($to, $subject, $message, $fromName);
                    $forgotModel->addError('success','Please check email to reset password.');
                } catch(Exception $e) {
                    $e->getMessage();exit;
                }
            } else {
                $forgotModel->addError('email','Email isn\'t exists in database.');
            }
        }

        $this->render('forgot', array('forgotModel' => $forgotModel));
    }

    public function actionUpload($id = null)
    {
        if($id == 0) {
            return "Vui lòng lưu nhập thông tin sản phẩm và lưu thông tin trước khi upload hình ảnh";
        }
        Yii::import("ext.EAjaxUpload.qqFileUploader");

        $folder=Yii::getPathOfAlias('webroot').'/data/upload/products/';// folder for uploaded files
        $allowedExtensions = array("jpg","jpeg","gif","png");//array("jpg","jpeg","gif","exe","mov" and etc...
        $sizeLimit = 500 * 1024 * 1024;// maximum file size in bytes
        $uploader = new qqFileUploader($allowedExtensions, 400000);
        $result = $uploader->handleUpload($folder);
        $return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);

        $fileSize=filesize($folder.$result['filename']);//GETTING FILE SIZE
        $fileName=$result['filename'];//GETTING FILE NAME
        
        $model=new Image;
        //$model->deleteAll('product_id =' . $id);
       
        $model->product_id = $id;
        $model->title = "Image upload";
        $model->filename= $result['filename'];
        if($model->save())
        {
            echo $return;// it's array
        }
    }
    
    public function actionReset($id) 
    {
        $user = Users::model()->findByPk($id);
        
        $pass = $this->generate_password(6);
        $data = array(
            'password' => $pass,
            'repeat_password' => $pass,
            'updated_time' => date('Y-m-d H:i:s'),
        );
        
        $user->attributes = $data;
        try {
            $user->save();
            $mailer = Yii::app()->Mailer;
            $mailer->ClearAddresses();
            $to = $user->email;
            $subject = 'Reset Password';
            $message = $this->renderPartial('reset_template', array('password' => $pass),true);
            $fromName = 'Petitpoint';
            $mailer->sendEmail($to, $subject, $message, $fromName);
        } catch (Exception $e) {
            //echo $e->getMessage();exit;
        }
        
        $this->render('reset');
    }
    
    function generate_password($length='')
    {
        $str='abcdefghijklmnopqrstuvwxyz0123456789';
        $max=strlen($str);
        $length=@round($length);
        if(empty($length)){$length=rand(8,12);}
        $password='';
        for($i=0; $i<$length; $i++){$password.=$str{rand(0,$max-1)};}
        return $password;
    }
}
